/**
 * @author JiuQi 玖柒
 * @date 2021/7/5 20:16
 * 二分查找
 */

public class T704 {
    public static void main(String[] args) {
        int[] nums = {-1, 0, 3, 5, 8, 9, 12};
        int target = 9;
        Solution704 solution = new Solution704();
        System.out.println(solution.search(nums, target));
    }
}

class Solution704 {
    public int search(int[] nums, int target) {
        if (target < nums[0] || target > nums[nums.length - 1]) {
            return -1;
        }
        int left = 0, right = nums.length - 1;
        System.out.println(right);
        while (left <= right) {
            //每次循环都要重新赋值mid
            int mid = left + ((right - left) / 2);
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }
}


//普通的查询方法
/*class Solution {
    public int search(int[] nums, int target) {
        boolean flag = false;
        int t = 0;
        int f = -1;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                t = i;
                flag = true;
            }
        }
        return flag ? t : f;
    }
}*/






























